import threading
import pgzrun
import time as tm
import tkinter as tk
import json as js

ROWS = 10
COLS = 10
world = []
CELL_SIZE = 7

def TK():
	global rows
	global cols
	global world
	
	top = tk.Tk()
	
	frames = []
	for i in range(3):
		frames.append(tk.Frame(top))
	for i in frames:
		i.pack()
	
	entries = []
	tk.Label(frames[0], text='rows:').pack(side='left')
	entries.append(tk.Entry(frames[0]))
	entries[0].pack(side='left')
	tk.Label(frames[1], text='cols:').pack(side='left')
	entries.append(tk.Entry(frames[1]))
	entries[1].pack(side='left')
	
	def Load():
		rows = entries[0].get()
		cols = entries[1].get()
	
	def Save():
		with open('world.json', 'w') as f:
			js.dump({'rows' : rows,
			'cols' : cols,
			'world' : world}, f)
	
	buttons = []
	buttons.append(tk.Button(frames[2], text='load', command=Load))
	buttons.append(tk.Button(frames[2], text='save', command=Save))
	for i in buttons:
		i.pack(side='left')
	
	top.mainloop(0)


def PyGameZero():
	HEIGHT = (ROWS * CELL_SIZE)
	WIDTH  = (COLS * CELL_SIZE + 90)

	BACK_COLOR = (0, 0, 50)

	def GenCellColor():
		return [random.randint(0, 50), random.randint(175, 250), random.randint(50, 100)]

	def init_map(rows, cols):
		return [[[0, BACK_COLOR] for c in range(cols)] for r in range(rows)]

	def save():
		files=os.listdir(".")
		x=0
		name=""
		while True:
			name="LifeGameMap"+str(x)+".json"
			if name not in files:
				break
			x+=1
		os.mknod(name)
		f=open(name,'w')
		f.write('{"size":['+str(ROWS)+','+str(COLS)+','+str(CELL_SIZE)+"],\n")
		f.write('"map":[\n')
		n=[]
		for i in range(len(world)):
			for j in range(len(world[i])):
				if not world[i][j][0]:
					continue
				o=("["+str(i)+','+str(j)+']')
				n.append(o)
		for i in range(len(n)):
			f.write(n[i])
			if i!=len(n)-1:
				f.write(',')
		f.write(']}')
			
		f.close()

	world = init_map(ROWS, COLS)
	on=[0,0]

	def get_cells(world):
		x=0
		for i in range(ROWS):
			for j in range(COLS):
				x+=world[i][j][0]
		return x

	def on_key_down(key):
		global world
		if key==keys.DELETE:
			world=init_map(ROWS,COLS)
		if key==keys.END:
			save()

	def on_mouse_down(pos):
		global world
		x=pos[1]//CELL_SIZE
		y=pos[0]//CELL_SIZE
		if y>=COLS:
			return
	#    print(x,y)
		world[x][y]=[int(not world[x][y][0]),GenCellColor()]

	def on_mouse_move(pos):
		global on
		x=pos[1]//CELL_SIZE
		y=pos[0]//CELL_SIZE
		if y>COLS:
			return
		on=[x,y]

	def draw_cell(w, r, c):
		cx = CELL_SIZE * c
		cy = CELL_SIZE * r
		cell_rect = Rect((cx, cy), (CELL_SIZE, CELL_SIZE))
		screen.draw.filled_rect(cell_rect, tuple(w[r][c][1]))

	def draw_line(w, r, c):
		cx = CELL_SIZE * c
		cy = CELL_SIZE * r
		line_rect = Rect((cx, cy), (CELL_SIZE+1, CELL_SIZE+1))
		screen.draw.rect(line_rect, (150,150,150))

	def update():
		pass

	def draw():
		screen.fill(tuple(BACK_COLOR))
		for r in range(ROWS):
			for c in range(COLS):
				if world[r][c][0]:
					draw_cell(world, r, c)
		for i in range(0,WIDTH-89,CELL_SIZE):
			screen.draw.line((i,0),(i,HEIGHT),(150,150,150))
		for i in range(0,HEIGHT,CELL_SIZE):
			screen.draw.line((0,i),(WIDTH-90,i),(150,150,150))
		screen.draw.text(('x:'+str(on[0]).zfill(2)), midtop=(1000,10))
		screen.draw.text(('y:'+str(on[1]).zfill(3)), midtop=(1005,30))
		n=get_cells(world)
		screen.draw.text(('cells:'+str(n).zfill(5)), midtop=(1027,50))
		screen.draw.text('Use delete', midtop=(1027,500))
		screen.draw.text('to clear  ', midtop=(1027,520))
		screen.draw.text('Use end to', midtop=(1027,540))
		screen.draw.text('save file ', midtop=(1027,560))

	pgzrun.go()
			




TK_ = threading.Thread(target=TK)
Py_ = threading.Thread(target=PyGameZero)
TK_.start()
Py_.start()
